<?php

/**
 * Services
 *
 * @package Controllers
 * @author  Vu Tran <vutran@perselab.com>
 * @since   Version 1.0
 */

define("IMAGE_UPLOAD_DIR", "tmp/recipe/images");

// Models
require_once './models/Image.php';
require_once 'ImageResizer.php';

class ImageController{
	
	public function loadImage($app, $id=0, $width=0, $height=0){
		$image = Model::factory('Image')->where_equal('id', $id)->find_one();
		$path = IMAGE_UPLOAD_DIR . '/' . $image->path;
		
		if($image instanceof Image){
			if($width == 0 && $height == 0){
				$cache_path = $path;
			}else{
				$cache_path = IMAGE_UPLOAD_DIR . '/resize/' . $width . '_' . $height . '_' . $image->path;
			}
			if(!file_exists($cache_path)){
				//$logger->info("Not cache this image yet: " . $path);
				
				$imageResizer = new ImageResizer();
				
				$imageResizer->load($path);
				
				if($width > 0 || $height > 0)
				{
					if($width > 0 && $height >0){
						$imageResizer->resize($width, $height);
					}else if($width > 0){
						$imageResizer->resizeToWidth($width);
					}else{
						$imageResizer->resizeToHeight($height);
					}
					$imageResizer->save($cache_path, $imageResizer->getImageType());
				}
			}
			
			$imageResizer = new ImageResizer();
			$imageResizer->load($cache_path);
			
			$imageType = 'image/png';
			if($imageResizer->getImageType() == IMAGETYPE_JPEG){
				$imageType = 'image/jpeg';	
			}else if($imageResizer->getImageType() == IMAGETYPE_GIF){
				$imageType = 'image/gif';
			}
			$imageResizer->output($imageResizer->getImageType());
			
			$response = $app->response();
			$response->header('Content-Type', $imageType);
			$response->header('Content-Disposition', 'inline; filename="'.$image->name.'"');
			
			$response->status(200);
			$response->write($imageResizer->getBuffering());
		}
	}
}